package com.haidong.web.request;

import com.haidong.mapper.UserMapper;
import com.haidong.pojo.User;
import com.haidong.util.SqlSessionFactoryUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

@WebServlet("/registerServlet")
public class registerServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受用户数据
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //将用户数据封装成用户对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        //获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        // 获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 获取mapper
        UserMapper um = sqlSession.getMapper(UserMapper.class);

        User flag = um.selectByName(username);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if(flag==null){
            um.add(user);
            sqlSession.commit();
            sqlSession.close();
            writer.write("<h1>添加成功</h1>");
        }else{
            writer.write("<h1>用户名已经存在</h1>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
